﻿// ===============================================================================
// DotNet.Platform 开发框架 2016 版权所有
// ===============================================================================

using System;
using System.Web.Mvc;
using DotNet.Extensions;
using DotNet.Utility;

namespace DotNet.EduWebApi
{
    [AttributeUsage(AttributeTargets.Method)]
    public class ApiCheckAttribute : BaseActionCheckAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.RequestContext.HttpContext.Request;

            var apikey = request.Form["_apikey"];
            var apikeyResult = CheckApiKey(apikey);
            if (apikeyResult.Failure)
            {
                Result(filterContext, apikeyResult);
                return;
            }

            var timestamp = request.Form["_timestamp"];
            var timestampResult = CheckTimeStamp(timestamp);
            if (timestampResult.Failure)
            {
                Result(filterContext, timestampResult);
                return;
            }

            base.OnActionExecuting(filterContext);
        }

        private BoolMessage CheckApiKey(string apikey)
        {
            var result = EncryptUtil.Decrypt(apikey);
            if (!result.Success)
            {
                return new BoolMessage(false, "无效的ApiKey");
            }
            apikey = result.Data.ToStringOrEmpty();
            if (apikey.Equals("af9af594629243b182a37a73f3d0e326"))
            {
                return BoolMessage.True;
            }
            return new BoolMessage(false, "无效的ApiKey");
        }

        private BoolMessage CheckTimeStamp(string timestamp)
        {
            //return BoolMessage.True;
            var result = EncryptUtil.Decrypt(timestamp);
            if (!result.Success)
            {
                return new BoolMessage(false, "无效的请求戳");
            }
            timestamp = result.Data.ToStringOrEmpty();
            if (Math.Abs(GetCurrentTimeMillis() - timestamp.ToDouble()) < 20 * 1000)
            {
                return BoolMessage.True;
            }
            return new BoolMessage(false, "无效的请求戳");
        }

        /// <summary>
        /// 获取时间戳(毫秒数)
        /// </summary>
        /// <returns>返回自1970年1月1日到目前为止的毫秒数</returns>
        private double GetCurrentTimeMillis()
        {
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return (DateTime.Now - startTime).TotalMilliseconds;
        }

        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        private string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
    }
}